package com.example.demo.controller;

import com.aliyun.oss.OSS;
import com.example.demo.configuration.AliyunOssConfig;
import com.example.demo.constant.TaskConstant;
import com.example.demo.controller.bean.Result;
import com.example.demo.dto.CommodityInfoDTO;
import com.example.demo.dto.CouponsRequestDTO;
import com.example.demo.mapper.entity.*;
import com.example.demo.service.CouponsManageService;
import com.example.demo.service.StudentCouponsService;
import com.example.demo.utils.PageBo;
import com.example.demo.utils.PageVo;
import com.example.demo.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api(value = "优惠券管理接口", tags = {"优惠券管理接口"})
@RequestMapping("couponsManage")
@RestController
@Slf4j
public class CouponsManageController {
    @Autowired
    private CouponsManageService service;

    private OSS ossClient;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StudentCouponsService studentCouponsService;

    @ResponseBody
    @ApiOperation(value = "获取代金券列表接口")
    @RequestMapping(value = "getVoucherList", method = {RequestMethod.POST})
    public Result<PageVo<CouponsView>> getVoucherList(@RequestBody PageBo pageBo) {
        PageVo<CouponsView> list = service.getVoucherList(pageBo);
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation(value = "获取满减劵列表接口")
    @RequestMapping(value = "getFullDiscountCouponList", method = {RequestMethod.POST})
    public Result<PageVo<CouponsView>> getFullDiscountCouponList(@RequestBody PageBo pageBo) {
        PageVo<CouponsView> list = service.getFullDiscountCouponList(pageBo);
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation(value = "获取折扣券列表接口")
    @RequestMapping(value = "getDiscountCouponList", method = {RequestMethod.POST})
    public Result<PageVo<CouponsView>> getDiscountCouponList(@RequestBody PageBo pageBo) {
        PageVo<CouponsView> list = service.getDiscountCouponList(pageBo);
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation(value = "获取折扣券列表接口")
    @RequestMapping(value = "getExchangeCouponList", method = {RequestMethod.POST})
    public Result<PageVo<CouponsView>> getExchangeCouponList(@RequestBody PageBo pageBo) {
        PageVo<CouponsView> list = service.getExchangeCouponList(pageBo);
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation(value = "搜索优惠券接口")
    @RequestMapping(value = "searchCouponList", method = {RequestMethod.POST})
    public Result<PageVo<CouponsView>> getCommoditySearch(@RequestBody CouponsView request) {
        PageBo pageBo = new PageBo();
        pageBo.setPageNum(request.getPageNum());
        pageBo.setPageSize(request.getPageSize());

        PageVo<CouponsView> logs = service.searchCouponList(request,pageBo);
        return Result.ok(logs);
    }

    @ApiOperation(value = "新增優惠券")
    @PostMapping("/addCoupons")
    public Result<String> addCoupons(@RequestParam("file") MultipartFile file, @RequestParam("addData") String addData) throws IOException {
        log.info(file.toString());

        CouponsRequestDTO coupons = new ObjectMapper().readValue(addData, CouponsRequestDTO.class);

        System.out.println("CouponsRequestDTO返回值"+coupons);

        log.info(file.toString());

        String originalFileName = file.getOriginalFilename();//从上传的文件中获取原始文件名
        int i = originalFileName.lastIndexOf(".");
        String png = originalFileName.substring(i);//获取文件扩展名

        //存储空间的名字
        String bucketName = "seedling-classmate";

        //创建存储对象
        ossClient = AliyunOssConfig.ossClient();

        //设置文件名并上传到OSS
        String fileName = "coupons/" + UUID.randomUUID().toString().substring(0,24)+png;
        ossClient.putObject(bucketName, fileName, file.getInputStream());   //之后在数据库中保存fileName

      // request.setProductImageUrl(fileName);
        ossClient.shutdown();
        return service.addCoupons(coupons,fileName);

    }


    @GetMapping("/getCompanyList")
    @ResponseBody
    public Result<List<CouponsView>> getAttributeList(){
        List<CouponsView> list = service.getCompanyList();
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation("優惠券詳情显示接口")
    @RequestMapping(value = "getCouponDetails/{couponsId}")
    public Result<List<CouponsView>> getCouponDetails(@PathVariable("couponsId")int couponsId){
        System.out.println("調用訂單詳情显示接口");
        List<CouponsView> list = service.getCouponDataList(couponsId);
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation("删除優惠券接口")
    @RequestMapping(value = "deleteCoupon", method = {RequestMethod.POST})
    public Result<String> delete(@RequestBody Coupons coupons) {
        return service.Coupons(coupons);
    }

    @ResponseBody
    @ApiOperation("批量删除接口")
    @RequestMapping(value ="batchDeleteCoupons", method = {RequestMethod.POST})
    public Result<String> batchDeleteCoupons(@RequestBody List<Coupons> couponsList) {
        service.batchDeleteCoupons(couponsList);
        return Result.ok("删除成功");
    }

    @ResponseBody
    @ApiOperation("修改優惠券狀態接口")
    @RequestMapping(value = "updateState", method = {RequestMethod.POST})
    public Result<String> updateState(@RequestBody CouponsView request) {
        return service.updateState(request);
    }

    @ResponseBody
    @ApiOperation("商品圖片显示接口")
    @RequestMapping(value = "findProductPic/{couponsId}")
    public Result<String> findCommodityPic(@PathVariable("couponsId")int couponsId) {
        Result<String> message = new Result<>();
        if (couponsId != 0) {
           // Coupons result = service.getById(couponsId);
            String imageUrl = service.getPicById(couponsId);
            if(imageUrl != null){
                message.setData("https://seedling-classmate.oss-cn-beijing.aliyuncs.com/" + imageUrl);
                return message;
            }
            else{
                return null;
            }
        }
        return null;
    }

    @ApiOperation(value = "商品圖片上传")
    @PostMapping("/updateProductPic")
    public Result uploadCommodity(@RequestParam("couponsId") int couponsId, @RequestParam("file") MultipartFile file) throws IOException {

        log.info(file.toString());

        String originalFileName = file.getOriginalFilename();//从上传的文件中获取原始文件名
        int i = originalFileName.lastIndexOf(".");
        String png = originalFileName.substring(i);//获取文件扩展名

        //存储空间的名字
        String bucketName = "seedling-classmate";

        //创建存储对象
        ossClient = AliyunOssConfig.ossClient();

        //设置文件名并上传到OSS
        String fileName = "coupons/" + UUID.randomUUID().toString().substring(0,24)+png;
        ossClient.putObject(bucketName, fileName, file.getInputStream());   //之后在数据库中保存fileName

        service.placeCouponsPic(couponsId, fileName);
        ossClient.shutdown();

        String result="http://seedling-classmate.oss-cn-beijing.aliyuncs.com/"+fileName;
        return Result.ok("上传成功",result);

    }
    @ApiOperation("核销优惠券")
    @GetMapping("/redeemCoupon/{couponsNumber}")
    public Result<String> redeemCoupon(@PathVariable String couponsNumber) {
        String value = null;
        if (redisUtil.hasKey(couponsNumber)) {
            value = (String) redisUtil.get(couponsNumber);
        } else {
            Result.warn("优惠券编码无效");
        }
        String[] parts = value.split(":");
        int studentId = Integer.parseInt(parts[1]);
        int couponsId = Integer.parseInt(parts[2]);
        studentCouponsService.updateStudentCouponsStatus(studentId, couponsId);
        redisUtil.del(couponsNumber);
        return Result.ok("核销成功");
    }

    @ResponseBody
    @ApiOperation(value = "获取學生優惠券列表接口")
    @RequestMapping(value = "getStudentCouponsList", method = {RequestMethod.POST})
    public Result<PageVo<StudentCoupons>> getStudentCouponsList(@RequestBody PageBo pageBo) {
        PageVo<StudentCoupons> list = service.getStudentCouponsList(pageBo);
        return Result.ok(list);
    }

    @ResponseBody
    @ApiOperation(value = "获取核销记录列表接口")
    @RequestMapping(value = "getRedeemList", method = {RequestMethod.POST})
    public Result<PageVo<StudentCoupons>> getRedeemList(@RequestBody PageBo pageBo) {
        PageVo<StudentCoupons> list = service.getRedeemList(pageBo);
        return Result.ok(list);
    }
}



